package com.si.control.action;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class SaveImageAction implements IAction<BufferedImage, Object> {

	private final JFileChooser chooser;

	public SaveImageAction() {
		this.chooser = new JFileChooser();
		this.chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
	}

	@Override
	public Object perform(final BufferedImage argument) throws Exception {
		// Select directory.
		final int result = this.chooser.showOpenDialog(null);
		if(result == JFileChooser.CANCEL_OPTION) return null;
		final File file = this.chooser.getSelectedFile();
		if(file == null) return null;
		if(file.isDirectory()) {
			final String name = JOptionPane.showInputDialog(null, "Please enter file name without extension:");
			final String filename = name.concat(".png");
			final File out = new File(file, filename);
			this.output(out, argument);
		} else this.output(file, argument);
		return null;
	}

	private void output(final File file, final BufferedImage image) throws Exception {
		if(file.exists()) {
			final int result = JOptionPane.showConfirmDialog(null, "Over-wirte existing file?");
			if(result == JOptionPane.CANCEL_OPTION || result == JOptionPane.NO_OPTION) return;
			file.delete();
		}
		file.createNewFile();
		ImageIO.write(image, "png", file);
	}
}
